#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Mosson"
import re
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from django.contrib.auth.hashers import make_password
from django_redis import get_redis_connection
from .models import User
from .utils import get_user_by_account

from order.models import Order


class UserModelSerializer(serializers.ModelSerializer):
    """
    服务端 提供数据给 客户端 这个叫序列化
    客户端 发送给    服务端叫做：反序列化
    write_only=True 表示只能用在反序列化阶段 服务端提供数据给客户端的时候不需要提供 sms—_code
    """

    sms_code = serializers.CharField(max_length=6, min_length=4, write_only=True, required=True, help_text="短信验证码")
    token = serializers.CharField(max_length=1024, read_only=True, help_text="token")

    class Meta:
        model = User
        fields = ["id", "username", "token", "password", "mobile", "sms_code"]
        extra_kwargs = {
            "id": {
                "read_only": True
            },
            "username": {
                "read_only": True
            },
            "password": {
                "write_only": True
            },
            "mobile": {
                "write_only": True
            },
            "": {}
        }

    def validate(self, attrs):
        """
        验证数据【验证手机号码的格式、验证手机好吗是不是被注册过、验证短信验证码是不是正确】
        :param attrs:
        :return:
        """
        mobile = attrs.get("mobile")
        sms_code = attrs.get("sms_code")
        password = attrs.get("password")
        # 验证手机格式
        if not re.match(r"^1[3-9]\d{9}$", mobile):
            raise serializers.ValidationError("手机号码格式有误！")
        # 验证手机号是不是已经被注册
        ret = get_user_by_account(mobile)
        if ret is not None:
            raise serializers.ValidationError("手机号码已经被注册！")
        # 验证短信验证码是不是正确
        redis_conn =  get_redis_connection("sms_code")
        real_sms_code = redis_conn.get("sms_%s" % mobile)
        #
        redis_conn.delete("sms_%s" % mobile)
        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError("对不起短息验证码错误，此次验证码已经失效，请重新发送！")
        return attrs

    def create(self, validated_data):
        """
        保存数据【在保存之前要将不需要入库的信息删除掉】
        :param kwargs:
        :return:
        """
        # 验证码 属于热频数据 不存数据库
        validated_data.pop("sms_code")
        # 密码加密
        raw_password = validated_data.get("password")
        hash_password = make_password(raw_password)
        # 设置默认的用户名
        username = validated_data.get("mobile")
        # 保存数据
        user = User.objects.create(
            mobile=username,
            username=username,
            password=hash_password
        )
        # 使用restframework_jwt模块手动生成 token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        user.token = jwt_encode_handler(payload)
        return user


class UserOrderModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = ["id","order_number","order_status","created_time","course_list"]